using System;
using UnityEngine;

public class PolyTerrainModuleDescriptor : MonoBehaviour
{
    private float _averageHeight;
    private readonly bool _initialized = false;
    public int[] CornerHeights;

    public bool Fit(int[] cornerHeights, out int rotationDegree)
    {
        InitializeIfNot();
        rotationDegree = 0;
        if (cornerHeights.Length != 4) return false;

        var cornersToFitAverage = GetAverage(cornerHeights);

        // early return if average not fit
        if (!Mathf.Approximately(cornersToFitAverage, _averageHeight)) return false;

        // find fit
        for (var i = 0; i < 4; i++)
        {
            var fit = true;
            for (var j = 0; j < 4; j++)
                if (cornerHeights[j] != CornerHeights[(j + i) % 4])
                    fit = false;

            if (fit)
            {
                rotationDegree = i * 90;
                return true;
            }
        }


        return false;
    }

    private void InitializeIfNot()
    {
        if (!_initialized)
        {
            if (CornerHeights.Length != 4) throw new Exception("Poly Terrain Module Not Initialized");
            _averageHeight = GetAverage(CornerHeights);
        }
    }

    private float GetAverage(int[] inputArray)
    {
        float average = 0;
        for (var i = 0; i < inputArray.Length; i++) average += inputArray[i];
        average /= inputArray.Length;
        return average;
    }
}